﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

#region Using
using System;
using System.Runtime.Remoting.Messaging;
using System.Net.Mail;
#endregion

namespace NetBay.Core.Tools
{
    public class EmailUtil
    {
        private string m_oSmtpServer;
        public string SmtpServer
        {
            set
            {
                m_oSmtpServer = value;
            }
        }


        #region Send sync mail
        public bool SendEmail(MailAddress p_sFrom, MailAddress p_sTo, string p_sSubject, string p_sBody)
        {
            Boolean l_bRet = false;
            try
            {
                MailMessage l_oMessage = new MailMessage(p_sFrom, p_sTo);
                l_oMessage.Subject = p_sSubject;
                l_oMessage.Body = p_sBody;
                SmtpClient pp = new SmtpClient(m_oSmtpServer);
                pp.Send(l_oMessage);
                l_bRet = true;
            }
            catch (Exception ehttp)
            {
                //TODO
                throw new Exception("Send error" + ehttp.Message);
            }
            return l_bRet;
        }
        #endregion

        #region Send Assync mail
        public delegate bool SendEmailDelegate(MailAddress p_sFrom, MailAddress p_sTo, string p_sSubject, string p_sBody);

        public void GetResultsOnCallback(IAsyncResult ar)
        {
            SendEmailDelegate del = (SendEmailDelegate)
             ((AsyncResult)ar).AsyncDelegate;
            try
            {
                bool l_bResult;
                l_bResult = del.EndInvoke(ar);
                //Debug.WriteLine("\nOn CallBack: result is " + l_bResult);
            }
            catch (Exception ex)
            {
                //TODO
                //Debug.WriteLine("\nOn CallBack, problem occurred: " + ex.Message);
            }
        }

        public void SendEmailAsync(MailAddress p_sFrom, MailAddress p_sTo, string p_sSubject, string p_sBody)
        {
            SendEmailDelegate dc = new SendEmailDelegate(this.SendEmail);
            AsyncCallback cb = new AsyncCallback(this.GetResultsOnCallback);
            IAsyncResult ar = dc.BeginInvoke(p_sTo, p_sTo,p_sSubject,p_sBody,  cb, null);
        }
        #endregion
    } 
}